import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { ApiProvider, TargetProvider } from '../interfaces/api-adapter.interface';
import { AdapterRegistryService } from '../core/adapter-registry.service';
import { GenericForwardingService } from '../core/generic-forwarding.service';
import { 
  MultiApiConfigDto, 
  UpdateApiRouteDto, 
  ApiRoutesResponseDto,
  BatchForwardRequestDto,
  BatchForwardResponseDto
} from '../dto/multi-api-config.dto';

/**
 * 多 API 配置管理服务
 */
@Injectable()
export class MultiApiConfigService {
  private readonly logger = new Logger(MultiApiConfigService.name);
  private readonly configFilePath: string;
  private readonly defaultConfig: MultiApiConfigDto;

  constructor(
    private readonly adapterRegistry: AdapterRegistryService,
    private readonly genericForwarding: GenericForwardingService
  ) {
    this.configFilePath = path.join(process.cwd(), '.multi-api-config.json');
    this.defaultConfig = {
      routes: [
        {
          provider: ApiProvider.ANTHROPIC,
          target: TargetProvider.COPILOT,
          enabled: true,
          description: 'Forward Anthropic Claude API to GitHub Copilot',
          config: {
            priority: 1,
            timeout: 30000,
            retryAttempts: 3
          }
        },
        {
          provider: ApiProvider.OPENAI,
          target: TargetProvider.COPILOT,
          enabled: false,
          description: 'Forward OpenAI GPT API to GitHub Copilot',
          config: {
            priority: 2,
            timeout: 30000,
            retryAttempts: 3
          }
        }
      ],
      defaultProvider: ApiProvider.ANTHROPIC,
      defaultTarget: TargetProvider.COPILOT,
      enableBatchProcessing: true,
      maxConcurrentRequests: 10,
      globalConfig: {
        logLevel: 'info',
        enableMetrics: true,
        enableTracing: false
      }
    };
  }

  /**
   * 获取多 API 配置
   */
  getMultiApiConfig(): MultiApiConfigDto {
    try {
      if (fs.existsSync(this.configFilePath)) {
        const content = fs.readFileSync(this.configFilePath, 'utf-8');
        const config = JSON.parse(content);
        return { ...this.defaultConfig, ...config };
      }
    } catch (error) {
      this.logger.warn(`Failed to load multi-API config: ${error.message}`);
    }
    
    return this.defaultConfig;
  }

  /**
   * 更新多 API 配置
   */
  async updateMultiApiConfig(config: Partial<MultiApiConfigDto>): Promise<{ success: boolean; message: string }> {
    try {
      const currentConfig = this.getMultiApiConfig();
      const updatedConfig = { ...currentConfig, ...config };
      
      // 验证配置
      this.validateConfig(updatedConfig);
      
      // 保存配置
      fs.writeFileSync(this.configFilePath, JSON.stringify(updatedConfig, null, 2), 'utf-8');
      
      this.logger.log('Multi-API configuration updated successfully');
      
      return {
        success: true,
        message: 'Multi-API configuration updated successfully'
      };
    } catch (error) {
      this.logger.error(`Failed to update multi-API config: ${error.message}`);
      throw new BadRequestException(`Failed to update configuration: ${error.message}`);
    }
  }

  /**
   * 获取所有可用的 API 路由
   */
  async getApiRoutes(): Promise<ApiRoutesResponseDto> {
    const config = this.getMultiApiConfig();
    const healthResults = await this.adapterRegistry.checkAllAdaptersHealth();
    
    const routes = config.routes.map(route => {
      const key = `${route.provider}->${route.target}`;
      const health = healthResults.get(key);
      
      return {
        provider: route.provider,
        target: route.target,
        enabled: route.enabled || false,
        description: route.description || `${route.provider} to ${route.target}`,
        healthStatus: health?.status || 'unhealthy',
        lastCheck: health?.lastCheck || new Date(),
        config: route.config
      };
    });
    
    const activeRoutes = routes.filter(r => r.enabled).length;
    const healthyRoutes = routes.filter(r => r.healthStatus === 'healthy').length;
    
    return {
      routes,
      totalRoutes: routes.length,
      activeRoutes,
      healthyRoutes
    };
  }

  /**
   * 更新特定 API 路由配置
   */
  async updateApiRoute(updateDto: UpdateApiRouteDto): Promise<{ success: boolean; message: string }> {
    try {
      const config = this.getMultiApiConfig();
      
      // 查找并更新路由
      const routeIndex = config.routes.findIndex(
        r => r.provider === updateDto.provider && r.target === updateDto.target
      );
      
      if (routeIndex === -1) {
        throw new BadRequestException(`Route ${updateDto.provider} -> ${updateDto.target} not found`);
      }
      
      // 更新路由配置
      if (updateDto.enabled !== undefined) {
        config.routes[routeIndex].enabled = updateDto.enabled;
      }
      
      if (updateDto.config) {
        config.routes[routeIndex].config = { 
          ...config.routes[routeIndex].config, 
          ...updateDto.config 
        };
      }
      
      // 保存配置
      return await this.updateMultiApiConfig(config);
    } catch (error) {
      this.logger.error(`Failed to update API route: ${error.message}`);
      throw new BadRequestException(`Failed to update API route: ${error.message}`);
    }
  }

  /**
   * 批量转发请求
   */
  async batchForward(batchDto: BatchForwardRequestDto, userInfo: any): Promise<BatchForwardResponseDto> {
    const startTime = Date.now();
    
    try {
      // 检查路由是否启用
      const config = this.getMultiApiConfig();
      const route = config.routes.find(
        r => r.provider === batchDto.provider && r.target === batchDto.target
      );
      
      if (!route || !route.enabled) {
        throw new BadRequestException(`Route ${batchDto.provider} -> ${batchDto.target} is not enabled`);
      }
      
      // 执行批量转发
      const results = await this.genericForwarding.forwardBatch(
        batchDto.provider,
        batchDto.target,
        batchDto.requests,
        userInfo,
        { ...route.config, ...batchDto.config }
      );
      
      // 统计结果
      const successfulRequests = results.filter(r => r.success).length;
      const failedRequests = results.length - successfulRequests;
      const totalDuration = Date.now() - startTime;
      const averageDuration = results.reduce((sum, r) => sum + r.duration, 0) / results.length;
      
      return {
        results: results.map(r => ({
          success: r.success,
          response: r.response,
          error: r.error?.message,
          duration: r.duration
        })),
        totalRequests: results.length,
        successfulRequests,
        failedRequests,
        totalDuration,
        averageDuration
      };
    } catch (error) {
      this.logger.error(`Batch forward failed: ${error.message}`);
      throw error;
    }
  }

  /**
   * 获取支持的 API 提供商和目标
   */
  getSupportedProvidersAndTargets(): {
    providers: ApiProvider[];
    targets: TargetProvider[];
    supportedCombinations: Array<{ provider: ApiProvider; target: TargetProvider }>;
  } {
    const supportedRoutes = this.adapterRegistry.getSupportedRoutes();
    
    const providers = Array.from(new Set(supportedRoutes.map(r => r.provider)));
    const targets = Array.from(new Set(supportedRoutes.map(r => r.target)));
    
    return {
      providers,
      targets,
      supportedCombinations: supportedRoutes
    };
  }

  /**
   * 启用/禁用 API 路由
   */
  async toggleApiRoute(
    provider: ApiProvider, 
    target: TargetProvider, 
    enabled: boolean
  ): Promise<{ success: boolean; message: string }> {
    return this.updateApiRoute({ provider, target, enabled });
  }

  /**
   * 获取 API 路由统计信息
   */
  async getApiRouteStats(): Promise<{
    totalRoutes: number;
    enabledRoutes: number;
    healthyRoutes: number;
    degradedRoutes: number;
    unhealthyRoutes: number;
    lastHealthCheck: Date;
  }> {
    const routesInfo = await this.getApiRoutes();
    
    const degradedRoutes = routesInfo.routes.filter(r => r.healthStatus === 'degraded').length;
    const unhealthyRoutes = routesInfo.routes.filter(r => r.healthStatus === 'unhealthy').length;
    const lastHealthCheck = routesInfo.routes.reduce(
      (latest, route) => route.lastCheck > latest ? route.lastCheck : latest,
      new Date(0)
    );
    
    return {
      totalRoutes: routesInfo.totalRoutes,
      enabledRoutes: routesInfo.activeRoutes,
      healthyRoutes: routesInfo.healthyRoutes,
      degradedRoutes,
      unhealthyRoutes,
      lastHealthCheck
    };
  }

  /**
   * 验证配置
   */
  private validateConfig(config: MultiApiConfigDto): void {
    if (!config.routes || config.routes.length === 0) {
      throw new Error('At least one route must be configured');
    }
    
    // 检查是否有重复的路由
    const routeKeys = new Set();
    for (const route of config.routes) {
      const key = `${route.provider}->${route.target}`;
      if (routeKeys.has(key)) {
        throw new Error(`Duplicate route found: ${key}`);
      }
      routeKeys.add(key);
      
      // 检查适配器是否存在
      if (!this.adapterRegistry.isSupported(route.provider, route.target)) {
        throw new Error(`Unsupported route: ${key}`);
      }
    }
    
    if (config.maxConcurrentRequests && config.maxConcurrentRequests < 1) {
      throw new Error('maxConcurrentRequests must be at least 1');
    }
  }
}